#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Copyright 2020 Huawei Technologies Co., Ltd
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
"""
import acl
import threading
import psutil
import logging
import sys
import os
import signal
from queue import Queue
from datetime import datetime
from .const import DEBUG, INFO, WARNING, ERROR, ACL_ERROR_NONE


class DemoLog():
    
    def __init__(self):
        self.now_time = datetime.now().strftime('%Y-%m-%d')
        self.filename = 'pyACL_demo-' + self.now_time+'.log'
        self.formatter = logging.Formatter('%(asctime)s-%(message)s')
        self.level = logging.ERROR
        self.logger = logging.getLogger('demo_log')
        self.console_handler = logging.StreamHandler(sys.stdout)
        self.file_handler = logging.FileHandler(self.filename)
        self.log_config()
        self.set_where_log_to(True, True)


    def log_config(self):
        self.console_handler.setLevel(level=self.level)
        self.console_handler.setFormatter(self.formatter)
        self.file_handler.setLevel(level=self.level)
        self.file_handler.setFormatter(self.formatter)
        self.logger.setLevel(level=self.level)


    def set_where_log_to(self, need_file: bool, need_console: bool):
        if need_console:
            self.logger.addHandler(self.console_handler) 
        if need_file:
            self.logger.addHandler(self.file_handler)


    def do_log(self, level, class_name, func_name,  message: str):
        pid = os.getpid()
        t = threading.currentThread()
        p_info = '[PID:' + str(pid) + ']'
        t_info = '[' + t.getName() + ']'
        func_msg = '[' + class_name + ']' + '[' + func_name + ']'
        total_message = p_info + t_info + func_msg + ':' + message
             
        if level == DEBUG:
            self.logger.debug(total_message)
        elif level == INFO:
            total_message = '[INFO]' + total_message
            self.logger.info(total_message)
        elif level == WARNING:
            total_message = '[WARNING]' + total_message
            self.logger.warning(total_message)
        elif level == ERROR:
            total_message = '[ERROR]' + total_message
            self.logger.error(total_message)


Log = DemoLog()


def check_ret(class_name, func_name, message, ret):
    if ret != ACL_ERROR_NONE:
        pid = os.getpid()
        ret_msg = message + '(ret ' + str(ret) + ')'
        Log.do_log(ERROR, class_name, func_name, ret_msg)
        os.kill(pid,signal.SIGINT)
        #signal.alarm(1)
        #raise Exception(ret_msg)
        #os._exit(1)
